package com.killer_jin.core.common.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 用于配置拦截器, 继承WebMVCConfigurerAdapter并重写addInterceptors方法或者 实现WebMvcConfigurer接口的addInterceptors方法
 * 都是可以的.
 * Created by Frank Wu on 16/4/9.
 */
@Configuration
public class InterceptorConf implements WebMvcConfigurer {
    @Autowired
    private UserApiInterceptor userApiInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 用户Interceptor
        registry.addInterceptor(userApiInterceptor).addPathPatterns("/api/v*/client/**").excludePathPatterns("/api/v*/client/cancel/**");

        // Todo 更多拦截器
    }

    /**
     * API跨域支持
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // you USUALLY want this
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        source.registerCorsConfiguration("/api/**", config);
        return new CorsFilter(source);
    }
}
